package ibms_rcp.company.parts;

import ibms_rcp.common.ChooseCompanyDialog;
import ibms_rcp.constants.Constants;
import ibms_rcp.dao.EstateManager;
import ibms_rcp.dao.LeaseManager;
import ibms_rcp.model.Building;
import ibms_rcp.model.Company;
import ibms_rcp.model.Floor;
import ibms_rcp.model.Lease;
import ibms_rcp.model.Room;
import ibms_rcp.util.PerspectiveUtils;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;

import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.nebula.widgets.calendarcombo.CalendarCombo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

public class EditLeasePart {

	//公司moi_id
	private Text idText;
	// 公司名称
	private Text nameText;
	// 选择公司
	private Button chooseCompanyButton;
	// 楼栋
	private ComboViewer buildingComboViewer;
	private Combo buildingCombo;
	// 楼层
	private ComboViewer floorComboViewer;
	private Combo floorCombo;
	// 房间
	private ComboViewer roomComboViewer;
	private Combo roomCombo;
	// 起租日期
	private CalendarCombo beginLeaseCombo;
	// 到租日期
	private CalendarCombo endLeaseCombo;
	// 开始收费日期
	private CalendarCombo chargeCombo;
	// 预收费功能开启单选框
	private Button onButton;
	// 预收费功能关闭单选框
	private Button offButton;
	// 物业费预收费复选框
	private Button propertyButton;
	// 电费预收费复选框
	private Button elecButton;
	//保存
	private Button saveButton;
	//取消
	private Button cancelButton;
	
	private Room room;
	private Lease lease;
	private Company company;
	
	@Inject private MApplication application;
	@Inject private EPartService partService;
	@Inject private EModelService modelService;
	@Inject private IEclipseContext context;

	/**
	 * 构造函数 注入父组件
	 * 
	 * @param parent
	 */
	@Inject
	public EditLeasePart(Composite parent) {
		room = new Room();
	}

	/**
	 * 添加控件
	 * 
	 * @param parent
	 */
	@PostConstruct
	public void createControls(final Composite parent) {
		GridLayout layout = new GridLayout(6, false);
		layout.marginWidth = 10;
		layout.marginHeight = 10;
		parent.setLayout(layout);
		
		// 公司名称
		Label nameLabel = new Label(parent, SWT.RIGHT);
		nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		nameLabel.setText("公司名称：");
		nameText = new Text(parent, SWT.BORDER);
		nameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				2, 1));
		nameText.setEditable(false);
		
		// 选择公司
		chooseCompanyButton = new Button(parent, SWT.NONE);
		chooseCompanyButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER,
				true, false, 1, 1));
		chooseCompanyButton.setText("选择公司");
		//点击弹出选择公司窗口
		chooseCompanyButton.addMouseListener(new MouseAdapter(){
			public void mouseUp(MouseEvent e) {
				ChooseCompanyDialog companyDialog = new ChooseCompanyDialog(parent.getShell());
				companyDialog.create();
				if (companyDialog.open() == Window.OK) {
					Company company = companyDialog.getCompany();
					if(company!=null){
						idText.setText(String.valueOf(company.getId()));
						nameText.setText(company.getName());
					}
				}
			}
		});
		
		//公司moi id
		idText = new Text(parent, SWT.BORDER);
		idText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		idText.setEditable(false);
		idText.setVisible(false);
		new Label(parent, SWT.NONE);
				
		// 楼栋
		Label buildingLabel = new Label(parent, SWT.RIGHT);
		buildingLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		buildingLabel.setText("楼栋：");
		buildingComboViewer = new ComboViewer(parent, SWT.READ_ONLY);
		buildingCombo = buildingComboViewer.getCombo();
		buildingCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		buildingComboViewer.setContentProvider(ArrayContentProvider
				.getInstance());
		buildingComboViewer.setLabelProvider(new LabelProvider() {
			@Override
			public String getText(Object element) {
				if (element instanceof Building) {
					Building building = (Building) element;
					return building.getEms_name();
				}
				return super.getText(element);
			}
		});
		// 模拟数据
		// Building[] buildings = new Building[] { new Building(1, "楼1", "1"),
		// new Building(2, "楼2", "2"), new Building(3, "楼3", "3") };
		// 获取楼数据
		buildingComboViewer.setInput(Constants.BUILDINGS);

		buildingComboViewer
				.addSelectionChangedListener(new ISelectionChangedListener() {
					@Override
					public void selectionChanged(SelectionChangedEvent event) {
						if(lease == null){//仅当添加租赁信息时联动，修改时不进行
							IStructuredSelection selection = (IStructuredSelection) event
									.getSelection();
							if(!selection.isEmpty()){//仅当添加租赁信息且非清空操作时
								long buildingId = ((Building) selection
										.getFirstElement()).getId();
								// 获取楼层数据
								List<Floor> floors = EstateManager
										.getFloorsByBuilding(buildingId);
								floorComboViewer.setInput(floors);
							}
						}
					}
				});

		// 楼层
		Label floorLabel = new Label(parent, SWT.RIGHT);
		floorLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		floorLabel.setText("楼层：");
		floorComboViewer = new ComboViewer(parent, SWT.READ_ONLY);
		floorCombo = floorComboViewer.getCombo();
		floorCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		floorComboViewer.setContentProvider(ArrayContentProvider.getInstance());
		floorComboViewer.setLabelProvider(new LabelProvider() {
			@Override
			public String getText(Object element) {
				if (element instanceof Floor) {
					Floor floor = (Floor) element;
					return floor.getEms_name();
				}
				return super.getText(element);
			}
		});

		floorComboViewer
				.addSelectionChangedListener(new ISelectionChangedListener() {
					@Override
					public void selectionChanged(SelectionChangedEvent event) {
						IStructuredSelection selection = (IStructuredSelection) event
								.getSelection();
						if(selection.isEmpty())
							return;
						long floorId = ((Floor) selection.getFirstElement())
								.getId();
						// 获取楼层数据
						List<Room> rooms = EstateManager.getRoomsByFloor(floorId);
						roomComboViewer.setInput(rooms);
					}
				});

		// 房间号
		Label roomLabel = new Label(parent, SWT.RIGHT);
		roomLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		roomLabel.setText("房间：");
		roomComboViewer = new ComboViewer(parent, SWT.READ_ONLY);
		roomCombo = roomComboViewer.getCombo();
		roomCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		roomComboViewer.setContentProvider(ArrayContentProvider.getInstance());
		roomComboViewer.setLabelProvider(new LabelProvider() {
			@Override
			public String getText(Object element) {
				if (element instanceof Room) {
					Room room = (Room) element;
					return room.getEms_name();
				}
				return super.getText(element);
			}
		});
		// 起租日期
		Label beginLeaseLabel = new Label(parent, SWT.RIGHT);
		beginLeaseLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER,
				false, false, 1, 1));
		beginLeaseLabel.setText("起租日期：");
		beginLeaseCombo = new CalendarCombo(parent, SWT.BORDER);
		beginLeaseCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		// 到租日期
		Label endLeaseLabel = new Label(parent, SWT.RIGHT);
		endLeaseLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		endLeaseLabel.setText("到租日期：");
		endLeaseCombo = new CalendarCombo(parent, SWT.BORDER);
		endLeaseCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		// 开始收费日期
		Label chargeLabel = new Label(parent, SWT.RIGHT);
		chargeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		chargeLabel.setText("开始收费：");
		chargeCombo = new CalendarCombo(parent, SWT.BORDER);
		chargeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		
		// 预收费功能开关
		Label switchLabel = new Label(parent, SWT.RIGHT);
		switchLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		switchLabel.setText("预收费功能：");
		Composite switchComposite = new Composite(parent, SWT.NONE);
		switchComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 3, 1));
		switchComposite.setLayout(new GridLayout(4, false));
		onButton = new Button(switchComposite, SWT.RADIO);
		onButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		onButton.setText("开通");
		onButton.setSelection(true);// 默认开启预收费功能
		offButton = new Button(switchComposite, SWT.RADIO);
		offButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		offButton.setText("关闭");
		onButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// 预收费开启时，可调置物业费和电费开关，关闭时不可设置
				boolean select = onButton.getSelection();
				propertyButton.setEnabled(select);
				elecButton.setEnabled(select);
			}
		});
		propertyButton = new Button(switchComposite, SWT.CHECK);
		propertyButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		propertyButton.setText("物业费");// 默认开启物业费预收费功能
		propertyButton.setSelection(true);
		elecButton = new Button(switchComposite, SWT.CHECK);
		elecButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		elecButton.setText("电费");
		elecButton.setSelection(true);// 默认开启电费预收费功能
		new Label(parent, SWT.NONE);
		new Label(parent, SWT.NONE);
		
		
		new Label(parent, SWT.NONE);
		new Label(parent, SWT.NONE);
		//保存
		saveButton = new Button(parent, SWT.NONE);
		saveButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		saveButton.setText("保存");
		saveButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				if(lease == null){//lease为null则为新加租赁信息
					//修改房间信息
					addRoomInfo(room);
					//保存
					long companyId = Long.valueOf(idText.getText());
					LeaseManager.addLease(companyId, room);
				}
				else{//否则为修改租赁信息
					Room room = new Room();
					room.setId(lease.getId());
					boolean preCharge = onButton.getSelection();
					room.setPreCharge(preCharge);//是否预收费
					if(preCharge){//如果预收费，设置物业费预收费和电费预收费
						room.setPropCharge(propertyButton.getSelection());
						room.setElecCharge(elecButton.getSelection());
					}
					LeaseManager.modifyLease(room);
				}
				if(company != null){//如果是从公司信息页面跳转过来，则跳转回去，否则不动
					//切换到company info的perspective
					PerspectiveUtils.switchToPerspective(application, modelService, partService, "ibms_rcp.perspective.company.info");
					System.out.println("saveButton mouse up.");
				}
			}
		});
		saveButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
				false, 1, 1));
		
		//取消
		cancelButton = new Button(parent, SWT.NONE);
		cancelButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		cancelButton.setText("取消");
		cancelButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				// 点击取消时
				if(company != null){//如果从公司信息页面跳转过来，则跳转回去
					//切换到company info的perspective
					PerspectiveUtils.switchToPerspective(application, modelService, partService, "ibms_rcp.perspective.company.info");
				}else{//否则只做清空操作
					clearInput();
				}
				System.out.println("cancelButton mouse up.");
			}
		});
		cancelButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true,
				false, 1, 1));
		new Label(parent, SWT.NONE);
		new Label(parent, SWT.NONE);

		System.out.println("EditLeasePart createControls called.");
	}

	@PreDestroy
	public void dispose() {
		System.out.println("EditLeasePart dispose called.");
	}

	/**
	 * 添加房间信息
	 * @param room
	 */
	public void addRoomInfo(Room room){
		IStructuredSelection selection = (IStructuredSelection) roomComboViewer.getSelection();
		room.setId(((Room) selection.getFirstElement()).getId());//room的moi id
		room.setBeginLeaseDate(beginLeaseCombo.getDateAsString());//始租日期
		room.setEndLeaseDate(endLeaseCombo.getDateAsString());//到租日期
		room.setBeginChargeDate(chargeCombo.getDateAsString());//开始收费日期
		boolean preCharge = onButton.getSelection();
		room.setPreCharge(preCharge);//是否预收费
		if(preCharge){//如果预收费，设置物业费预收费和电费预收费
			room.setPropCharge(propertyButton.getSelection());
			room.setElecCharge(elecButton.getSelection());
		}
	}
	
	/**
	 * 清空输入
	 */
	public void clearInput(){
		nameText.setText("");
		idText.setText("");
		chooseCompanyButton.setVisible(true);
		buildingComboViewer.setSelection(null);
		floorComboViewer.setSelection(null);
		roomComboViewer.setSelection(null);
		beginLeaseCombo.setText("");
		endLeaseCombo.setText("");
		chargeCombo.setText("");
		onButton.setSelection(true);
		propertyButton.setSelection(true);
		elecButton.setSelection(true);
		buildingCombo.setEnabled(true);//允许编辑
		floorCombo.setEnabled(true);
		roomCombo.setEnabled(true);
		beginLeaseCombo.setEnabled(true);
		endLeaseCombo.setEnabled(true);
		chargeCombo.setEnabled(true);
	}
	
	/**
	 * 显示租赁信息视图时，根据context中的lease进行显示
	 */
	@Focus
	public void updateDisplay(){
		System.out.println("EditLeasePart updateDisplay called.");
		lease = (Lease)application.getContext().get("lease");
		company = (Company)application.getContext().get("company");
		//lease与company的值是是否为null有4种组合，其中3种可能出现且合逻辑，而lease不为null,company为null的情况不会出现
		//1)lease不为null，company不为null， 修改已有租赁信息
		//2)lease为null, company不为null, 对某公司添加租赁信息（从公司信息页面跳转过来）
		//3)lease为null, company为null, 添加租赁信息（从租赁登记菜单项跳转过来）
		room = new Room();
		//更新基本信息显示
		if(lease!=null){//编辑已有租赁信息
			//显示company的moi id和name,隐藏选择公司按钮
			idText.setText(String.valueOf(company.getId()));
			nameText.setText(String.valueOf(company.getName()));
			chooseCompanyButton.setVisible(false);
			//显示楼、层、房间数据
			List<Building> buildings = Constants.BUILDINGS;
			Building building = null;
			for(int i=0; i<buildings.size(); i++){
				building = buildings.get(i);
				if(building.getEms_id().equals(String.valueOf(lease.getBuildingId()))){
					buildingComboViewer.setSelection(new StructuredSelection(building));
					break;
				}
			}
			List<Floor> floors = EstateManager.getFloorsByBuilding(building.getId());
			floorComboViewer.setInput(floors);
			Floor floor = null;
			for(int i=0; i<floors.size(); i++){
				floor = floors.get(i);
				if(floor.getEms_id().equals(String.valueOf(lease.getFloorId()))){
					floorComboViewer.setSelection(new StructuredSelection(floor));
					break;
				}
			}
			List<Room> rooms = EstateManager.getRoomsByFloor(floor.getId());
			roomComboViewer.setInput(rooms);
			Room room;
			for(int i=0; i<rooms.size(); i++){
				room = rooms.get(i);
				if(room.getEms_id().equals(String.valueOf(lease.getRoomId()))){
					roomComboViewer.setSelection(new StructuredSelection(room));
					break;
				}
			}
			//显示起租、到租、收费时间信息
			beginLeaseCombo.setText(lease.getFromDate());
			endLeaseCombo.setText(lease.getToDate());
			chargeCombo.setText(lease.getChargeDate());
			buildingCombo.setEnabled(false);//不允许编辑房间、日期信息
			floorCombo.setEnabled(false);
			roomCombo.setEnabled(false);
			beginLeaseCombo.setEnabled(false);
			endLeaseCombo.setEnabled(false);
			chargeCombo.setEnabled(false);
			onButton.setSelection(lease.isPreCharge());//只能编辑预收费、物业费、电费等
			offButton.setSelection(!lease.isPreCharge());
			if(onButton.getSelection()){
				propertyButton.setSelection(lease.isPropCharge());
				elecButton.setSelection(lease.isElecCharge());
			}
		}
		else if(company!=null){//对某公司添加租赁信息（从公司信息页面跳转过来）
			//显示company的moi id和name,隐藏选择公司按钮
			idText.setText(String.valueOf(company.getId()));
			nameText.setText(String.valueOf(company.getName()));
			chooseCompanyButton.setVisible(false);
		}
		else{//添加租赁信息（从租赁登记菜单项跳转过来）
			clearInput();//清空输入System.out.println(((Floor)((IStructuredSelection)buildingComboViewer.getSelection()).getFirstElement()).getId());
		}
	}
}
